import React, { useEffect, useMemo, useState } from 'react';
import { Modal, Input, Collapse } from 'antd';
import styled from '@emotion/styled';
import useSyncState from '../hooks/useSyncState';
import { useTTSBoardCast } from '../Context/TTSBoardCastContext';
import { useTranslation } from 'react-i18next';
import VariableTabs from './Variable/index';
import TinymceTextarea from './TinymceTextarea';
import TTSSelect from './TTSSelect';
import TextAreaContent from './TextAreaContent';

const TTSTextArea = styled(Input.TextArea)`
	resize: none;
	height: 243px;
	background: #f6f6f6;
	border-radius: 4px;
	position: relative;
	textarea {
		resize: none;
	}
`;

const TTSCollapse = styled(Collapse)`
	.ant-collapse-item {
		.ant-collapse-header {
			padding: 12px 0;
		}
	}
`;

const TTSPanel = styled(Collapse.Panel)`
	.ant-collapse-content {
		.ant-collapse-content-box {
			height: 100%;
			padding: 0 !important;
		}
	}
`;

const VariableContainer = styled.div`
	display: flex;
	height: 120px;
	flex-wrap: wrap;
	overflow-y: auto;
`;

const VariableBox = styled.div`
	height: fit-content;
	min-height: 50px;
	border-radius: 4px;
	border: ${(props: { content: string }) => (props.content ? '1px solid #e1e2e5' : '0')};
	margin-right: 10px;
	margin-bottom: 10px;
	background: ${(props: { content: string }) => (props.content ? '#ffffff' : '#F3F3F3')};
	:hover {
		border: ${(props: { content: string }) => (props.content ? '1px solid #252b48' : '0')};
		cursor: ${(props: { content: string }) => (props.content ? 'pointer' : 'no-drop')};
	}
`;

const VariableContent = styled.div`
	padding: 6px 8px;
	width: 100%;
	height: fit-content;
`;

const VariableTitle = styled.p`
	margin: 0;
	padding: 0;
	font-size: 12px;
	color: #2d2d2d;
`;

const VariableText = styled.p`
	margin: 0;
	padding: 0;
	font-size: 12px;
	color: #b0b0b0;
	word-break: break-all;
    height: fit-content;
    display: inline-block;
`;

const Empty = styled.p`
	font-size: 12px;
	color: #b0b0b0;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0;
`;

const Error = styled.p`
	font-size: 12px;
	color: #f8646a;
	margin-bottom: 0;
	margin-top: 4px;
`;

const EditModal = (props: { ttsOptions: { id: number; title: string; content: string }[]; onPopupScroll: (event: any) => void }) => {
	const { ttsOptions = [], onPopupScroll } = props;
	const { t } = useTranslation();
	const { TTSBoardCastText, setTTSBoardCastText, EditModal, setEditModal, startTTSPassAgeway, setBoardCastModal, selectedVariableList, getVariableValue, variableList } = useTTSBoardCast();

	const [errorMessage, setErrorMessage] = useSyncState('');
	const [insertText, setInsertText] = useState<string>('');

	const [selectTTSConent, setSelectTTSConent] = useState<string | undefined>(undefined);

	useEffect(() => {
		if (EditModal()) {
			setTTSBoardCastText('');
			getVariableValue();
			setErrorMessage('');
			setSelectTTSConent(undefined);
		}
	}, [EditModal()]);

	const onChange = (value: string) => {
		setTTSBoardCastText(value);
		setInsertText('');
	};

	const handleOk = () => {
		setTTSBoardCastText(TTSBoardCastText().replace(/\s+/g, ''));
		if (!selectTTSConent && !TTSBoardCastText()) {
			setErrorMessage('*' + t('enter-broadcast-text'));
			return;
		}
		setEditModal(false);
		startTTSPassAgeway();
		console.log('selectTTSConent:', selectTTSConent);

		if (!selectTTSConent) {
			replaceTTSBoardCastText();
		} else {
			replaceSelectedTTSText();
		}

		setBoardCastModal(true);

		// setTTSBoardCastStats('stow');
	};

	const handleCancel = () => {
		setEditModal(false);
	};

	// 字符串中插入字符
	const insertStr = (soure: string, dom: any, newStr: string) => {
		const soureCurrent = soure === null ? '' : soure;
		console.log({ soure, dom, newStr });
		if (dom && dom.setSelectionRange) {
			const start = dom.selectionStart;
			const newStrLength = newStr.length;
			setTimeout(() => {
				dom.focus();
				dom.setSelectionRange(start + newStrLength, start + newStrLength, 'none');
			});
			return soureCurrent.slice(0, start) + newStr + soureCurrent.slice(start);
		} else {
			setInsertText(newStr);
		}
	};

	const clickVariable = (value: string) => {
		const selectedVariable = variableList().find((item: any) => item.id === value);
		if (!selectedVariable.value) return;
		const data = `${selectedVariable.roleId ? '客户信息' : '业务信息'}_${selectedVariable.roleName}_${selectedVariable.name}_${selectedVariable.id}`;
		let textareaDom = document.getElementById('tts-textarea');
		insertStr(TTSBoardCastText(), textareaDom, `{{${data}}}`);
		// setTTSBoardCastText();
	};

	//替换播报文案
	const replaceTTSBoardCastText = () => {
		const textarea = document.getElementById('tts-textarea');
		if (!textarea) return;
		let template = textarea.innerText.replace(/{{([^}}]+)?}}/g, function (key, content) {
			let value = key.substring(2, key.length - 2);
			let data = value.split('_');
			let text = variableList().find((item: any) => item.id === Number(data[data.length - 1]));
			return text && text.value ? (content = text.value) : (content = '');
		});
		setTTSBoardCastText(template);
	};

	// 替换固定播报文案
	const replaceSelectedTTSText = () => {
		const textarea = document.getElementById('tts-textarea');
		if (!textarea) return;
		let template = textarea.innerText.replace(/{{([^}}]+)?}}/g, function (key, content) {
			let value = key.substring(2, key.length - 2);
			let data = value.split('_');
			let text = variableList().find((item: any) => item.id === Number(data[data.length - 1]));
			return text && text.value ? (content = text.value) : (content = '');
		});
		console.log(template, 'textarea');

		setTTSBoardCastText(template);
	};

	// 选择播报话术
	const selectTTS = (id: number) => {
		const talk = ttsOptions.find(item => item.id === id);
		if (talk?.content) {
			let template = talk?.content.replace(/{{([^}}]+)?}}/g, function (key, content) {
				let strs = key.substring(2, key.length - 2);
				let id = strs.split('_');
				content = `<span class="mceNonEditable" contenteditable="false">{{${id.slice(0, id.length - 1).join('_')}<span class="mce-hide">_${id[id.length - 1]}}}</span></span>`;
				return content;
			});

			setSelectTTSConent(template);
			setErrorMessage('');
		} else {
			setSelectTTSConent(undefined);
		}
	};

	// 渲染TTS内容
	const renderTTSConent = useMemo(() => {
		if (selectTTSConent) {
			return (
				<>
					<TinymceTextarea insertText={''} id="tts-textarea" value={selectTTSConent} showCount={true} maxLength={2000} disabled={true} />
					{errorMessage() ? <Error>{errorMessage()}</Error> : undefined}
				</>
			);
		} else {
			return (
				<>
					<TinymceTextarea
						id="tts-textarea"
						value={TTSBoardCastText()}
						showCount={true}
						maxLength={2000}
						onChange={onChange}
						placeholder={t('enter-broadcast-text') as string}
						insertText={insertText}
						disabled={false}
					/>
					{errorMessage() ? <Error>{errorMessage()}</Error> : undefined}
					<TTSCollapse ghost>
						<TTSPanel header={t('insert-variable')} key="1">
							<VariableTabs />
							<VariableContainer>
								{variableList().length === 0 ? (
									<Empty>{t('no-variable-available')}</Empty>
								) : (
									<>
										{selectedVariableList().map((item: any) => {
											return (
												<VariableBox key={item.id} onClick={() => clickVariable(item.id)} content={item.value}>
													<VariableContent>
														<VariableTitle>{`${item.linkedKey}(${item.name})`}</VariableTitle>
														<VariableText>{t('value') + `：${item.value ? item.value : '- -'}`}</VariableText>
													</VariableContent>
												</VariableBox>
											);
										})}
									</>
								)}
							</VariableContainer>
						</TTSPanel>
					</TTSCollapse>
				</>
			);
		}
	}, [selectTTSConent, TTSBoardCastText(), variableList(), selectedVariableList(), insertText, errorMessage()]);

	return (
		<Modal
			title={t('tts-broadcast')}
			open={EditModal()}
			onOk={handleOk}
			onCancel={handleCancel}
			width={600}
			cancelText={t('cancel')}
			okText={t('start-broadcast')}
			destroyOnClose={true}
			maskClosable={false}
		>
			<div className="tts-container-textArea">
				{/* <TTSTextArea id="tts-textarea" value={TTSBoardCastText()} showCount bordered={false} maxLength={2000} onChange={onChange} placeholder={t('enter-broadcast-text') as string} /> */}
				<TTSSelect onPopupScroll={onPopupScroll} options={ttsOptions} disabled={false} onChange={selectTTS}></TTSSelect>
				{renderTTSConent}
			</div>
		</Modal>
	);
};

export default EditModal;
